<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;

/**
 * 日报接口
 */
class Daily extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['createcomplaint'];
    public function _initialize()
    {
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
        $this->dailys=model('admin/daily/Dailys');
        $this->readylog=model('admin/daily/Readylog');
        $this->youbiao=model('admin/daily/Youbiao');
        $this->user=model('admin/User');
        $this->department=model('admin/Department');
        $this->checkindata=model('admin/Checkindata');
    }

    /**
     * 提交日报
     */
    public function  createDailys($id=null,$content,$user_ids,$goout_type_name,$stay_type_name,
                                  $continuousnum,$goOutAccumulatenum,$visitnum,$kaoqinnum,$checkindata_id,
                                  $youbiao=null,$images=null,$desc=null){

        if($id){
            if(!$dailysInfo= $this->dailys->get(['id'=>$id,'date'=>date('Y-m-d',time())])){
                $this->error('未找到您提交的日报');
            }
            Db::startTrans();
            try {
                $data=['user_id'=>$this->auth->id,'title'=>$this->auth->username."提交日报",'content'=>$content,'user_ids'=>$user_ids,
                    'date'=>date('Y-m-d',time()),'goout_type_name'=>$goout_type_name,'stay_type_name'=>$stay_type_name,
                    'continuousnum'=>$continuousnum,'goOutAccumulatenum'=>$goOutAccumulatenum,'visitnum'=>$visitnum,'kaoqinnum'=>$kaoqinnum,'checkindata_id'=>$checkindata_id];
                $dailysInfo->save($data);
                //清除原来的日志记录
                $this->readylog->where('daily_dailys_id',$id)->delete();
                if($user_ids!=''){
                    $readylogdataall=[];
                    foreach (explode(",",$user_ids) as $key=>$value){
                        $logdata['daily_dailys_id']=$id;
                        $logdata['user_id']=$value;
                        $readylogdataall[]=$logdata;
                    }
                    $this->readylog->saveAll($readylogdataall);
                }
                //日报提交后检测油表信息
                if($youbiao!=null){
                    $youbiaodata=['youbiao'=>$youbiao,'images'=>$images,'desc'=>$desc,'user_ids'=>$user_ids,'daily_dailys_id'=>$id,'user_id'=>$this->auth->id];

                    if($youbiaoInfo=$this->youbiao->get(['daily_dailys_id'=>$id])){
                        if($youbiaoInfo->youbiao!=$youbiao ||  $youbiaoInfo->images==$images ||  $youbiaoInfo->desc==$desc){
                            $youbiaodata['status']='审批中';
                            $youbiaoInfo->save($youbiaodata);
                        }else{
                            if(in_array($youbiaoInfo->status,['审批中','未通过'])){
                                $youbiaodata['status']='审批中';
                                $youbiaoInfo->save($youbiaodata);
                            }
                        }

                    }else{
                        $this->youbiao::Create($youbiaodata);
                    }
                }

                Db::commit();

                $this->success('日报修改成功');

            } catch (Exception $e) {
                $this->setError($e->getMessage());
                Db::rollback();
                return false;
            }


        }else {

            if ($this->dailys->get(['user_id' => $this->auth->id, 'date' => date('Y-m-d', time())])) $this->error('今日已提交日报请勿重复提交');
            $data = ['user_id' => $this->auth->id, 'title' =>$this->auth->username."提交日报", 'content' => $content, 'user_ids' => $user_ids,
                'date' => date('Y-m-d', time()), 'goout_type_name' => $goout_type_name, 'stay_type_name' => $stay_type_name,
                'continuousnum'=>$continuousnum,'goOutAccumulatenum'=>$goOutAccumulatenum,'visitnum'=>$visitnum,'kaoqinnum'=>$kaoqinnum,'checkindata_id'=>$checkindata_id];;
            Db::startTrans();
            try {
                $re = $this->dailys::Create($data);
                if ($user_ids != '') {
                    $readylogdataall = [];
                    foreach (explode(",", $user_ids) as $key => $value) {
                        $logdata['daily_dailys_id'] = $re->id;
                        $logdata['user_id'] = $value;
                        $readylogdataall[] = $logdata;
                    }
                    $this->readylog->saveAll($readylogdataall);
                }
                //日报提交后检测油表信息
                if ($youbiao != null) {
                    $data = ['youbiao' => $youbiao, 'images' => $images, 'desc' => $desc, 'user_ids' => $user_ids, 'daily_dailys_id' => $re->id,'user_id'=>$this->auth->id];
                    $this->youbiao::Create($data);
                }
                Db::commit();
                $this->success('日报提交成功');

            } catch (Exception $e) {
                $this->setError($e->getMessage());
                Db::rollback();
                return false;
            }
            //检测当前会员今日是否提交过

        }

    }

    /**
     * 我的/团队日报
     * @param int $page
     * @param int $limit
     */
    public function  myDailysList($page=1,$limit=10,$date=null,$user_id=null){
     //   $where['user_id']=['=',$this->auth->id];  //读取的日报是抄送给我的或者我的日报
        if($date!=null){
            $where['date']=['=',$date];
        }

        if($user_id!=null){
            $where['user_id']=['=',$user_id];
        }


       $dailysList= $this->dailys->where($where)->order('date desc')->paginate($limit);
        foreach ($dailysList as $key=>$value){

            $where1['id']=['in',explode(",",$value['user_ids'])];
            $dailysList[$key]['chaosonguserList']=implode(",",$this->user->where($where1)->column('username')); //抄送人
            $dailysList[$key]['readyedList']=implode(",",$this->readylog
                ->alias('r')
                ->join('__USER__ u','r.user_id = u.id')
                ->where('r.daily_dailys_id',$value['id'])
                ->where('r.status','已读')
                ->column('username'));
            $dailysList[$key]['createtime']=date('Y-m-d H:i:s',$value['createtime']);
        }
        $this->success('OK',$dailysList);

    }

    /**
     *
     */
   public  function DailysDateils($id){

     if($DailysDateils= $this->dailys->get($id)){
         $where1['id']=['in',explode(",",$DailysDateils['user_ids'])];

         $DailysDateils['chaosonguserList']=implode(",",$this->user->where($where1)->column('username')); //抄送人
         $DailysDateils['readyedList']=implode(",",$this->readylog
             ->alias('r')
             ->join('__USER__ u','r.user_id = u.id')
             ->where('r.daily_dailys_id',$DailysDateils['id'])
             ->where('r.status','已读')
             ->column('username'));
         $DailysDateils['createtime']=date('Y-m-d H:i:s',$DailysDateils['createtime']);
         //发起人信息
         $userInfo=$this->user->where('id',$DailysDateils->user_id)->field('id,username,avatar,position,department_ids')->find();
         $departmentWhere['id']=['in',explode(",",$userInfo['department_ids'])];
         $userInfo['departmentList']=implode(",",$this->department->where($departmentWhere)->column('name'));
         $DailysDateils['userinfo']=$userInfo;
         $DailysDateils['checkindata']= $this->checkindata->where('id',$DailysDateils->checkindata_id)
             ->field('groupname,checkin_time,checkin_type,exception_type,location_title,location_detail,lat,lng')->find();
         
         $this->success('OK',$DailysDateils);
     }else{
         $this->error('日报不存在');
     }

   }




}
